﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace QLNHDAO
{
    public class Repository<T> : IRepository<T> where T : class
    {
        public QLNhaHangDataContext Db;

        public Repository()
        {
            Db = new QLNhaHangDataContext();
        }

        public IEnumerable<T> All()
        {
            return GetTable;
        }

        public IEnumerable<T> SearchFor(Expression<Func<T, bool>> predicate)
        {
            return GetTable.Where(predicate);
        }

        public void Add(T entity)
        {
            GetTable.InsertOnSubmit(entity);
            SaveChange();
        }
        public void Delete(T entity)
        {
            GetTable.DeleteOnSubmit(entity);
            SaveChange();
        }
        public void Update(T entity)
        {
            try
            {
                // create a new instance of the object
                Object newObj = Activator.CreateInstance(typeof(T),new object[0]);
                PropertyDescriptorCollection originalProps = TypeDescriptor.GetProperties(entity);
                // set the new object to match the passed in object

                foreach (PropertyDescriptor currentProp in originalProps)
                {
                    if (currentProp.Attributes[typeof(ColumnAttribute)] !=null)
                    {
                        object val = currentProp.GetValue(entity);
                        currentProp.SetValue(newObj, val);
                    }
                }
                // attach the new object to a new data context and
                // call submit changes on the contex t

                using (var datacontext = new QLNhaHangDataContext())
                {
                    var table = datacontext.GetTable<T>();
                    table.Attach((T)newObj, true);
                    datacontext.SubmitChanges();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        private void SaveChange()
        {
            Db.SubmitChanges();
        }
        private Table<T> GetTable
        {
            get { return Db.GetTable<T>(); }
        }
    }
}
